#include "customer.h"
#include "ui_customer.h"
#include <QMessageBox>

const QString Customer::QUERY_ALL_CUSTOMERS = QString::fromUtf8("SELECT id, nombre AS 'Nombre', apellido AS 'Apellido', calle AS 'Calle', numero AS \'Número\', piso AS 'Piso', departamento AS 'Departamento', telefono AS \'Teléfono\', email AS 'Email', observaciones AS 'Observaciones' FROM cliente");

Customer::Customer(QWidget *parent) :QWidget(parent),ui(new Ui::Customer){
    ui->setupUi(this);

    connect(ui->btnSave, SIGNAL(clicked()), this, SLOT(accept()));
    connect(ui->btnCancel, SIGNAL(clicked()), this, SLOT(close()));

    centerOnScreen();
    this->setWindowTitle("Clientes");
}

void Customer::centerOnScreen(){

    this->setWindowFlags(Qt::WindowStaysOnTopHint);

    QRect rect = this->frameGeometry();
    rect.moveCenter(QDesktopWidget().availableGeometry().center());
    this->move(rect.topLeft());
    qApp->processEvents();
}

void Customer::getCustomers(QSqlQueryModel *model){

    model->clear();
    model->setQuery(QUERY_ALL_CUSTOMERS);
}

void Customer::setCustomer(QString id){

    _currentCustomerId = id;
    loadCustomer();
}

bool Customer::hasPedidos(QString id)
{
    QString query = "SELECT id FROM pedido WHERE cliente="+id;

    QSqlQueryModel *model = DBConnection::Instance()->getModel(query);
    return (model->rowCount() > 0);
}

void Customer::deleteCustomer(QString id){

    if (hasPedidos(id))
    {
        const int result = QMessageBox::warning(this, "Eliminar cliente", "Atención: el cliente ha realizado pedidos!\n\nSi elimina este cliente, se eliminarán todos sus pedidos asociados! Desea continuar?", QMessageBox::Yes, QMessageBox::No);

        if(result == QMessageBox::Yes){
            const QString query = "DELETE FROM pedido WHERE cliente = " + id;
            DBConnection::Instance()->execQuery(query);
            emit updateOrders();
        }
        else
        {
            return;
        }
    }
    QString query = "DELETE FROM cliente WHERE id = " + id;
    DBConnection::Instance()->execQuery(query);
    emit updateCostumer();
}

void Customer::clearForm(){

    ui->lineEditName->setText("");
    ui->lineEditLastname->setText("");
    ui->lineEditAddress->setText("");
    ui->lineEditAddressNumber->setText("");
    ui->lineEditAddressFloor->setText("");
    ui->lineEditAddressApartment->setText("");
    ui->lineEditPhone->setText("");
    ui->lineEditEmail->setText("");
    ui->textEditObservations->clear();
}

void Customer::loadCustomer(){

    QSqlQueryModel* model = DBConnection::Instance()->getModel(QUERY_ALL_CUSTOMERS + " WHERE id = " + _currentCustomerId);

    ui->lineEditName->setText(model->record(0).value("nombre").toString());
    ui->lineEditLastname->setText(model->record(0).value("apellido").toString());
    ui->lineEditAddress->setText(model->record(0).value("calle").toString());
    ui->lineEditAddressNumber->setText(model->record(0).value("numero").toString());
    ui->lineEditAddressFloor->setText(model->record(0).value("piso").toString());
    ui->lineEditAddressApartment->setText(model->record(0).value("departamento").toString());
    ui->lineEditPhone->setText(model->record(0).value("telefono").toString());
    ui->lineEditEmail->setText(model->record(0).value("email").toString());
    ui->textEditObservations->setPlainText(model->record(0).value("observaciones").toString());
    qDebug() << QUERY_ALL_CUSTOMERS;
}

void Customer::accept(){

    QString query;
    QStringList params;

    ui->lineEditAddressNumber->setText(ui->lineEditAddressNumber->text() == "" ? "0" : ui->lineEditAddressNumber->text());
    ui->lineEditAddressFloor->setText(ui->lineEditAddressFloor->text() == "" ? "0" : ui->lineEditAddressFloor->text());

    params << "'" + ui->lineEditName->text() + "'" << "'" + ui->lineEditLastname->text() + "'" <<
              "'" + ui->lineEditAddress->text() + "'" << ui->lineEditAddressNumber->text() <<
              ui->lineEditAddressFloor->text() << "'" + ui->lineEditAddressApartment->text() + "'" <<
              "'" + ui->lineEditPhone->text() + "'" << "'" + ui->lineEditEmail->text() + "'" <<
              "'" + ui->textEditObservations->toPlainText() + "'";

    if (_currentCustomerId != ""){

        query = "UPDATE cliente SET nombre = " + params.at(0) +
                "," + "apellido = " + params.at(1) +
                "," + "calle = " + params.at(2) +
                "," + "piso = " + params.at(3) + "," +
                "numero = " + params.at(4) + "," +
                "departamento = " + params.at(5) + "," +
                "telefono = " + params.at(6) + "," +
                "email = " + params.at(7) + "," +
                "observaciones = " + params.at(8) +
                " WHERE id = " + _currentCustomerId;
    }
    else{

        query = "INSERT INTO cliente (nombre, apellido, calle, numero, piso, departamento, telefono, email, observaciones) VALUES (";

        for (int i=0; i < params.size() -1; i++){
            query = query + params.at(i) + ",";
        }

        query = query + params.at(params.size() -1) + ")";
    }

    DBConnection::Instance()->execQuery(query);
    emit updateCostumer();
    close();
}

void Customer::close(){

    _currentCustomerId = "";
    clearForm();
    QWidget::close();
}

Customer::~Customer(){
    delete ui;
}
